import { Form, Input, Button, Checkbox, Card, message } from 'antd'
import logo from '../../assets/logo.png'
import styles from './index.module.scss'
import { useDispatch } from 'react-redux'
import { login } from '@/store/actions/login.js'
import { useState } from 'react'
import { useHistory } from 'react-router-dom'

const Login = () => {
  const history = useHistory()
  const [bol, setBol] = useState(false)
  const dispatch = useDispatch()
  const sumit = async (val) => {
    console.log(val)
    // 验证成功发送请求
    const { mobile, code } = val
    try {
      setBol(true)
      // await 等待异步执行完毕再执行后续代码
      await dispatch(login({ mobile, code }))
      message.success('登录成功', 0.5, () => {
        console.log(history.location)
        history.push(history.location.state?.from || '/home')
      })
    } catch (error) {
      message.error(error.response.data.message, 0.5)
    } finally {
      setBol(false)
    }
  }
  return (
    <div className={styles.root}>
      <Card className="login-container">
        {/* 图片 */}
        <img className="login-logo" src={logo} alt="" />
        {/* 表单 */}
        <Form
          autoComplete="off"
          size="large"
          // 表单提交事件
          onFinish={sumit}
          // 默认值
          initialValues={{
            mobile: 13811111111,
            code: '246810',
            agree: true
          }}>
          <Form.Item
            name="mobile"
            // 表单验证, 必须有name属性
            rules={[
              { pattern: /^1\d{10}$/, message: '手机号不合法' },
              { required: true, message: '必填' }
            ]}>
            <Input placeholder="请输入手机号" />
          </Form.Item>

          <Form.Item
            name="code"
            rules={[
              { pattern: /^\d{6}$/, message: '验证码不合法' },
              { required: true, message: '必填' }
            ]}>
            <Input placeholder="请输入验证码" />
          </Form.Item>

          <Form.Item
            name="agree"
            // 设置value属性为checked
            valuePropName="checked"
            rules={[
              {
                // 自定义表单验证
                validator (rule, value) {
                  if (value) return Promise.resolve()
                  return Promise.reject(new Error('霸王条款必须填'))
                }
              }
            ]}>
            <Checkbox>我已阅读并同意[隐私条款]和[用户协议]</Checkbox>
          </Form.Item>

          <Form.Item>
            <Button loading={bol} type="primary" htmlType="submit" block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Login
